package org.example.yunpicturebackend.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;
import org.example.yunpicturebackend.config.CosClientConfig;
import org.example.yunpicturebackend.exception.BusinessException;
import org.example.yunpicturebackend.exception.ErrorCode;
import org.example.yunpicturebackend.manager.CosManager;
import org.example.yunpicturebackend.model.dto.file.UploadPictureResult;


import javax.annotation.Resource;
import java.io.File;

import java.util.Date;
import java.util.List;

/**
 * 图片上传模板
 * 定义公共的流程
 * todo:这种设计使用了模板方法模式，将固定的上传流程放在父类中，而将可能变化的部分（如图片的校验、
 *      获取原始文件名、处理文件的方式）抽象出来，由子类实现。
 */
@Slf4j  public abstract class PictureUploadTemplate {

    @Resource
    protected CosManager cosManager;

    @Resource
    protected CosClientConfig cosClientConfig;

    /**
     * 模板方法，定义上传流程
     *  final修饰，防止子类重写整个流程
     */
    public final UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 1. 校验图片
        validPicture(inputSource);

        // 2. 图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originFilename = getOriginFilename(inputSource);

        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originFilename));
        // 确保后缀不为空
        if (StrUtil.isBlank(FileUtil.getSuffix(originFilename))) {
            // 如果没有后缀，使用默认后缀
            uploadFilename = uploadFilename + "jpg";
            // 或者根据文件类型判断
        }
        // 3. 图片上传路径
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        System.out.println("----------inputSource----------: " + inputSource);
        System.out.println(inputSource);
        File file = null;
        try {
            // 创建临时文件
            file = File.createTempFile(uploadPath, null);
            // 处理文件来源（本地或 URL）
            processFile(inputSource, file);
            // 上传图片到对象存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            /**
             * putObjectResult: 上传返回结果
             * .getCiUploadResult(): 获取内容识别（CI）处理结果
             * .getOriginalInfo(): 获取原图信息
             * .getImageInfo(): 获取图片的元数据信息
             * 作用: 提取原图的宽度、高度、格式等基本信息
             * 返回数据示例:
             * json
             * {
             *   "width": 800,
             *   "height": 600,
             *   "format": "jpg",
             *   "size": 102400
             * }
             */
//            这个列表里只有一个元素
            List<CIObject> objectList = processResults.getObjectList();
            String originUrl ="";
            if (inputSource instanceof String) {
                // URL上传：原图URL就是传入的URL
                originUrl = (String) inputSource;
            } else {
                // 文件上传：原图URL由COS的域名和上传路径组成
                originUrl = cosClientConfig.getHost() + "/" + uploadPath;
            }

            //：如果图片处理结果列表不为空，就获取第一个（压缩后的）图片对象。
                if (CollUtil.isNotEmpty(objectList)) {
                    //获取压缩图
                    CIObject compressedCiObject = objectList.get(0);
                    //缩略图=压缩图
                    CIObject  thumbnailCiObject=compressedCiObject;
                    if(objectList.size()>1){
                        //缩略图等于规格的缩略图
                    thumbnailCiObject= objectList.get(1);
                    }
                    // 封装压缩图返回结果
                    // 拼写原图地址
                  //  originUrl = cosClientConfig.getHost() + "/" + uploadPath;

                    System.out.println(uploadPath);
                    return buildResult(originFilename, compressedCiObject, originUrl,thumbnailCiObject);
                }

            // 封装原图返回结果
            return buildResult(originFilename, file, originUrl, imageInfo);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }finally {
            // 6. 清理临时文件
            deleteTempFile(file);
        }
    }
    /**
     * 校验输入源（本地文件或 URL）
     */
    protected abstract void validPicture(Object inputSource);

    /**
     * 获取输入源的原始文件名
     */
    protected abstract String getOriginFilename(Object inputSource);

    /**
     * 处理输入源并生成本地临时文件
     */
    protected abstract void processFile(Object inputSource, File file) throws Exception;

    /**
     * 条件：当腾讯云COS返回了压缩图列表时（即图片被成功压缩）
     *封装返回结果
     * @param originFilename
     * @param compressedCiObject 压缩后的图片对象
     * @param originUrl 原图路径
     * @param thumbnailCiObject 缩略图对象
     * @return
     */
    private UploadPictureResult buildResult(String originFilename,CIObject compressedCiObject,String originUrl,CIObject thumbnailCiObject) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        //原图地址
        uploadPictureResult.setOriginUrl(originUrl);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        // todo：设置图片为压缩后的地址
        //compressedCiObject.getKey() 是腾讯云COS返回的压缩图的存储路径
        //compressedCiObject.getKey() = "public/123/2024-01-15_abc123.webp"
        //完整URL = https://bucket.cos.ap-beijing.myqcloud.com/public/123/2024-01-15_abc123.webp
        //特点：
         uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
         //设置缩略图URL
         uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        return uploadPictureResult;
    }
    /**
     * 封装返回结果
     * 条件：当没有压缩图时（即图片未被压缩处理）
     */
    private UploadPictureResult buildResult(String originFilename, File file, String uploadPath, ImageInfo imageInfo) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        uploadPictureResult.setOriginUrl(uploadPath);
        return uploadPictureResult;
    }

    /**
     * 删除临时文件
     */
    public void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }
}